package com.ming.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.ming.entity.TbRole;
import com.ming.entity.TbUser;
import com.ming.exception.PermissionException;
import com.ming.param.LoginParam;
import com.ming.param.UPpassword;
import com.ming.service.TbFunctionService;
import com.ming.service.TbUserService;
import com.ming.shiro.CustomSessionManager;
import com.ming.util.BeanValidator;
import com.ming.util.JsonData;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.SerializationUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author MING
 * @date 2018/8/10 11:09
 */
@Controller
public class LoginController {
    @Autowired
    HttpServletRequest request;

    @Autowired
    private TbFunctionService tbFunctionService;
    @Autowired
    private TbUserService tbUserService;

    /**
     * 登录操作
     * @param loginParam
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public JsonData login(@ModelAttribute("loginParam") LoginParam loginParam) {
        BeanValidator.check(loginParam);
//        判断验证码
//        String pageCaptcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//        if (!pageCaptcha.equals(loginParam.getCaptcha())) {
//            return JsonData.fail("验证码错误！");
//        }
//        获取到主体
        Subject subject = SecurityUtils.getSubject();
//        主体提交请求
        UsernamePasswordToken token = new UsernamePasswordToken(loginParam.getUserName(), loginParam.getPassword());
        try {
//            设置为记住我
            token.setRememberMe(loginParam.isRememberMe());
//            登录
            subject.login(token);
        } catch (IncorrectCredentialsException e) {
            throw new PermissionException("密码错误！");
        }catch (UnknownAccountException p){
            throw new PermissionException("用户错误！");
        }
//        TbUser tbUser = tbUserService.login(loginParam.getUserName());
//        String s = JSONObject.toJSONString(tbUser);
//        request.getSession().setAttribute("TbUser", s);
        Session session = SecurityUtils.getSubject().getSession();
        TbUser attribute = (TbUser) session.getAttribute((session.getId().toString()).getBytes());
        return JsonData.success("登录成功！");
    }


    /**
     * 跳转到中心界面
     * @return
     */
    @RequestMapping(value = "/center", method = RequestMethod.GET)
    public String center() {
        return "/WEB-INF/jsp/home";
    }

    /**
     * 跳转到中心页面后，进行树的菜单展示操作
     */
    @RequestMapping(value = "function" ,method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getRole_Function(){
        return tbFunctionService.getFunction_URL();
    }


    /**
     * 退出
     * @return
     */
    @RequestMapping(value = "/exit", method = RequestMethod.GET)
    public String exit() {
        return "forward:/index.jsp";
    }

    /**
     * 跳转到修改密码界面
     * @return
     */
    @RequestMapping(value = "/password", method = RequestMethod.GET)
    public  String change_Password(Model model){
        model.addAttribute("userName", SecurityUtils.getSubject().getPrincipal());
        return "/changePwd/changePwd";
    }

    /**
     * 更新密码
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public JsonData update_Password(@ModelAttribute("uPpassword") UPpassword uPpassword){
        JsonData jsonData = tbUserService.UPpassword(uPpassword ,request);
        return jsonData;
    }
}
